// 全局定义一次
layui.config({
    //base: window.location.protocol + '//' + window.location.host + '/public/static/'
    base: APP.STATIC + 'static/'
}).extend({
    // xmSelect: '../plugins/layui-xmSelect/xm-select', // 加载 xmSelects(旧版本formSelects)
    echarts: '../../plugins/echarts/echarts', // 加载 echarts
    echartsTheme: '../../plugins/echarts/echartsTheme',
    notice: '../plugins/layui-notice/notice',
    viewer: '../../plugins/viewer/js/viewer',
    tinymce: '../../plugins/layui-tinymce/tinymce', // tinymce 富文本编辑器
});

layui.use(['element', 'layer', 'form', 'jquery', 'util', 'notice', 'viewer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    var util = layui.util;

    var Notice = layui.notice; // 允许别名 toastr
    var Viewer = layui.viewer;


    // 返回顶部
    util.fixbar({
        top: true,
        css: {right: 35, bottom: 15},
        //bgcolor: '#2a96ff !important;display:block;',
        //bgcolor: '#9F9F9F !important; display:block;', // 自定义区块背景色
        //showHeight: 300, // 用于控制出现TOP按钮的滚动条高度临界值。默认：200
        click: function (type) {
            if (type === 'top') {
                $('.layui-body').animate({
                    scrollTop: 0
                }, 200);
            }
        }
    });

    // 关闭 iframe
    $(document).on('click', '.close-btn', function () {
        parent.layer.close(layer.index);
        var indexLay = parent.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引
        parent.layer.close(indexLay);
    });


    // 清除缓存
    $(document).on('click', '.refresh-btn', function () {
        var index = layer.msg('操作中，请稍候', {icon: 16, time: false, shade: 0.8});

        var url = $(this).attr('data-url');
        $.get(
            url,
            function (res) {
                layer.close(index);
                if (res.code == 1) {
                    //layer.msg('清除缓存成功！3秒后自动刷新页面');
                    COMMON.notice(Notice).success('清除缓存成功！3秒后自动刷新页面');
                    setTimeout('window.location.reload()', 3000);
                }
            }
        );
    });

    // 个人中心
    $(document).on('click', '#view-profile', function () {
        var content = $(this).attr('data-url');
        var index = layer.open({
            title: "个人中心",
            type: 2,
            area: ["600px", "500px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    });

    // 修改密码
    $(document).on('click', '#view-reset_password', function () {
        var content = $(this).attr('data-url');
        var index = layer.open({
            title: "修改密码",
            type: 2,
            area: ["600px", "400px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    });

    // 批量导出
    $(document).on('click', '#export_csv', function () {
        var _this = $(this);
        var url = $(this).data('url');
        var data = $(this).parents('form').serialize();

        var index = top.layer.msg('数据下载中，请稍候', {icon: 16, time: false, shade: 0.8});
        $.ajax({
            url: url,
            data: data,
            type: "post",
            dataType: "json",
            success: function (res) {
                layer.close(index);
                if (res.code == 1) {
                    // 方式一
                    //document.location = res.data;
                    var iframe = $('<iframe/>', {'src': res.data.url}).hide();
                    _this.append(iframe);
                    layer.msg(res.msg);
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    });

    var galley = document.getElementsByClassName('viewer-photos');
    if (galley.length > 0) {
        for (var i = 0; i < galley.length; i++) {
            console.log(galley[i]);
            var viewer = new Viewer(galley[i], {
                url: 'layer-src',
            });
        }
    }
    $(document).on('click', '.viewer-video', function () {
        var src = $(this).find('video').attr('src');
        var content = '<div class="video-modal"><div class=""><video class="video-box" src="' + src+ '" autoplay="autoplay" controls="controls"></video></div></div>';
        layer.open({
            title: '查看视频',
            type: 1,
            area: ['600px', '500px'],
            content: content
        });
    });
});

var COMMON = function () {
    var viewer = '';
    var viewer_flag = false;

    return {
        notice: function (Notice, config) {
            var $config = {
                closeButton: true,//显示关闭按钮
                debug: false,//启用debug
                positionClass: "toast-top-right",//弹出的位置,
                showDuration: "300",//显示的时间
                hideDuration: "1000",//消失的时间
                timeOut: "2000",//停留的时间
                extendedTimeOut: "1000",//控制时间
                showEasing: "swing",//显示时的动画缓冲方式
                hideEasing: "linear",//消失时的动画缓冲方式
                iconClass: 'toast-info', // 自定义图标，有内置，如不需要则传空 支持layui内置图标/自定义iconfont类名
                onclick: null, // 点击关闭回调
            };
            $config = Object.assign($config, config);
            // 初始化配置，同一样式只需要配置一次，非必须初始化，有默认配置
            Notice.options = $config;
            return Notice;
        },

        // 查看图片
        viewImage: function (Viewer, galley, url = 'layer-src') {
            if (viewer_flag) {
                viewer.destroy();
            }

            if (galley.length > 0) {
                for (var i = 0; i < galley.length; i++) {
                    viewer = new Viewer(galley[i], {
                        url: url
                    });
                    viewer_flag = true;
                }
            }
        },

        // 查看视频
        viewVideo: function (layer, src) {
            var content = '<div class="video-modal"><div class=""><video class="video-box" src="' + src+ '" autoplay="autoplay" controls="controls"></video></div></div>';
            layer.open({
                title: '查看视频',
                type: 1,
                area: ['600px', '500px'],
                content: content
            });
        },

        // 自定义表单
        ajaxTable: function (layui, url, data, page, limit, table_elm, page_elm) {
            var loading = layer.load(2);
            if (!page) {
                page = 1;
            }
            if (!limit) {
                limit = 20;
            }
            if (!data) {
                data = {};
            }
            if (!table_elm) {
                table_elm = layui.$('.layui-table-box');
            }
            if (!page_elm) {
                page_elm = document.getElementsByClassName('layui-table-page')[0];
            }
            data.page = page;
            data.limit = limit;
            layui.$.post(url, data, function (res) {
                layer.close(loading);
                if (res.code == 0) {
                    table_elm.find('tbody').html(res.html);
                    layui.form.render();
                    // 分页
                    layui.laypage.render({
                        //elem: 'tablePage',
                        elem: page_elm,
                        count: res.count,
                        limit: limit,
                        limits: [10, 20, 50, 100],
                        curr: page,
                        prev: '<i class="layui-icon layui-icon-left"></i>',
                        next: '<i class="layui-icon layui-icon-right"></i>',
                        layout: ['first', 'prev', 'page', 'next', 'last', 'skip', 'count', 'limit'],
                        jump: function (obj, first) {
                            // first（是否首次） -- 首次不执行
                            if (!first) {
                                COMMON.ajaxTable(layui, url, data, obj.curr, obj.limit);
                            }
                        }
                    });
                } else {
                    layer.msg(res.msg);
                }
            })
        },
    };
}();

Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
// 删除数组指定的某个元素
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

function stringLines(f) {
    return f.toString().replace(/^[^\/]+\/\*!?\s?/, '').replace(/\*\/[^\/]+$/, '');
}

// 文件下载
function download_file($, src) {
    var url = $('.download_url').val();
    var tempwindow = window.open('_blank');
    //tempwindow.location = url;
    tempwindow.location = url += '?file=' + src;
}

// 验证数据格式
function verify_data(value, type = 'require') {
    var value = value.trim();

    switch (type) {
        // 非空验证
        case 'require':
            return !!value;
            break;
        // 汉字验证
        case 'ecode':
            return /^[^\u4e00-\u9fa5]{0,}$/.test(value);
            break;
        // 手机号验证
        case 'phone':
            return /^1(3|4|5|6|7|8|9)[0-9]\d{8}$/.test(value);
            break;
        // 手机号验证(包含座机)
        case 'phone1':
            return /^400-[0-9]{3}-[0-9]{4}|^800-[0-9]{3}-[0-9]{4}|^1(3|4|5|6|7|8|9)([0-9]{9})|^0[0-9]{2,3}-[0-9]{8}$/.test(value);
            break;
        // 邮箱验证
        case 'email':
            return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
            break;
        // 验证非零的正整数
        case 'integer':
            return /^\+?[1-9][0-9]*$/.test(value);
            break;
        // 验证1-10的正数
        case 'number_1_10':
            return /^([1-9]|10)\.?\d*$/.test(value);
            break;
        // 验证正数
        case 'number':
            return /^(([0-9]+[\.]?[0-9]+)|[1-9])$/.test(value);
            break;
        // 验证金额
        case 'money':
            return /^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(value);
            break;
        default: break;
    }
}
